import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/post_api.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cloud_medicine/pages/post_detail.dart';
import 'package:cloud_medicine/components/author_show.dart';
import 'package:cloud_medicine/model/post_list.dart';

class PostList extends StatefulWidget {
  @override
  _PostListState createState() => _PostListState();
}

class _PostListState extends State<PostList> {
  List<PostItem> _postList = [];
  bool showMoreLoading = false; // 上拉加载状态
  ScrollController _scrollController = ScrollController();
  int _page = 1; // 页数

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    _loadData();
  }

  @override
  void dispose() {
    _scrollController.dispose(); // 销毁监听器
    super.dispose();
  }

  // 加载更多数据
  Future<Null> _loadData() async {
    setState(() {
      showMoreLoading = true;
    });
    dynamic res = await getPostList_api('$backIP/post/list', {'page': _page});
    res['data'].forEach((dynamic postItem) {
      PostItem postItemModel = PostItem.init(postItem);
      _postList.add(postItemModel);
    });
    if (mounted) {
      setState(() {
        showMoreLoading = false;
        if (res['data'].length != 0) {
          _page = _page + 1;
        }
      });
    }
  }

  // 下拉刷新，请求第一页的数据
  Future<Null> _refresh() async {
    _postList.clear(); // 清除当前帖子数组状态数据
    setState(() {
      _page = 1;
    });
    _loadData();
    Fluttertoast.showToast(
      msg: '刷新成功',
      backgroundColor: Colors.grey[300],
      textColor: Colors.lightBlueAccent,
    );
    return;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh,
      color: Theme.of(context).primaryColor,
      displacement: 40, // 指示器显示时距顶部位置
      child: ListView.builder(
          shrinkWrap: true,
          controller: _scrollController,
          itemCount: _postList.length + 1,
          itemBuilder: (context, index) {
            if (index == _postList.length) {
              return loadingWidget(showMoreLoading);
            } else {
              return Material(
                color: Colors.transparent,
                child: InkWell(
                  splashColor: Colors.yellow.withOpacity(0.3), // 慢慢展开的颜色
                  highlightColor: Colors.yellow.withOpacity(0.1), // 高亮颜色
                  onTap: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(
                            builder: (context) => PostDetail(
                                  postID: _postList[index].id,
                                )))
                        .then((value) {
                      _refresh();
                    });
                  },
                  child: Container(
                    color: Colors.white,
                    padding: EdgeInsets.all(8),
                    margin: EdgeInsets.only(bottom: 10),
                    child: new ListView(
                      shrinkWrap: true,
                      physics: new NeverScrollableScrollPhysics(),
                      children: <Widget>[
                        AuthorShow(
                          userID: _postList[index].authorBasicInfo.id,
                          realname: _postList[index].authorBasicInfo.realname,
                          avatar: _postList[index].authorBasicInfo.avatar,
                          createTime: _postList[index].createTime,
                        ),
                        SizedBox(height: 10),
                        Text(
                          _postList[index].abstract,
                          maxLines: 3,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Icon(
                              Icons.favorite_border,
                              color: Colors.grey,
                            ),
                            SizedBox(width: 5),
                            Text(
                              _postList[index].like_num,
                              style: TextStyle(color: Colors.grey),
                            ),
                            SizedBox(width: 10),
                            Icon(
                              Icons.mode_comment,
                              color: Colors.grey,
                            ),
                            SizedBox(width: 5),
                            Text(
                              _postList[index].comment_num,
                              style: TextStyle(color: Colors.grey),
                            )
                          ],
                        ),
                        SizedBox(
                          height: 10,
                        )
                      ],
                    ),
                  ),
                ),
              );
            }
          }),
    );
  }
}
